from flask import Flask, abort, request, render_template
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)

class Config:
    '''配置参数'''
    SQLALCHEMY_DATABASE_URI = "mysql://root:123456@localhost:3306/flask_db"
    # SQLALCHEMY_ECHO = True
# 将数据库配置匹配到到FLask
app.config.from_object(Config)
# 创建数据库连接对象
db = SQLAlchemy(app)
class User(db.Model):
    __tablename__="user"
    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(10),unique=True)
    password = db.Column(db.String(16))

    def __repr__(self):
        return f'(id={self.id} username="{self.username}" password="{self.password}")'

def add_user(name,psd):
    user=User(username=name,password=psd)
    db.session.add(user)
    db.session.commit()

def find_user(name):
    user_info = User.query.filter(User.username == name).all()
    return user_info


@app.route("/login",methods=["GET","POST"])

def login():
    if request.method =="GET":
        return render_template("login.html")
    if request.method =="POST":
        username = request.form.get("username")
        password = request.form.get("password")
        print(username)
        print(password)
        if username =="":
            return "请输入用户名"
        if password =="":
            return "请输入密码"
        user_info = find_user(username)
        if user_info:
            if user_info[0].password == password:
                return "登录成功"
        else:
            return "用户名或密码错误"


@app.route("/register",methods=["GET","POST"])

def register():
    if request.method == "GET":
        return  render_template("register.html")
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        password2 = request.form.get("password2")
        if not username or not password or not password2:
            return "请填写完整信息", 400
        if password != password2:
            return "两次密码输入不一致", 400
        if len(password) < 3:
            return "密码长度至少3位", 400
        if find_user(username):
            return "用户名已存在", 409
        add_user(username,password)
        return render_template("login.html")

if __name__ == '__main__':
    app.run()